package cn.zhuama.org.service.impl;

import cn.zhuama.basic.sevice.impl.BaseServiceImpl;
import cn.zhuama.basic.util.Md5Utils;
import cn.zhuama.basic.util.PageList;
import cn.zhuama.basic.util.StrUtils;
import cn.zhuama.org.domain.Employee;
import cn.zhuama.org.domain.Logininfo;
import cn.zhuama.org.mapper.EmployeeMapper;
import cn.zhuama.org.mapper.LogininfoMapper;
import cn.zhuama.org.query.EmployeeQuery;
import cn.zhuama.org.service.EmployeeService;
import cn.zhuama.system.mapper.RoleMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.List;

@Service
//查询的方法比较多，使用查询的事务配置
//只读，事务传播机制=SUPPORTS，有我就用，没有事务就不用
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements EmployeeService {
    @Autowired
    EmployeeMapper employeeMapper;

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    LogininfoMapper logininfoMapper;



    @Override
    public void add(Employee T) {
        //添加同时要更新中间表 员工和角色之间的
        //这个中间表用于关联 到时候好从中间找
        //这里面要实现业务逻辑
        //密码加密
        //作为盐salt
        T.setSalt(StrUtils.getRandomString(4));
        T.setPassword(Md5Utils.encrypByMd5(T.getSalt()+T.getPassword()));
        //得再给个type

        //将user同步复制到loginfo信息
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(T, logininfo);
        //给个type
        logininfo.setType(0);
        logininfoMapper.save(logininfo);
        //将logininfo的id放到user封装一下吧这里
        T.setLogininfo_id(logininfo.getId());
        employeeMapper.saveRegis(T);
        employeeMapper.saveEmploymRole(T.getId(),T.getRole_id());

    }

    @Override
    public void update(Employee T) {
        //修改对应的logininfo表
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(T,logininfo);
        logininfoMapper.update(logininfo);
        //自己更新
        super.update(T);
    }

    @Override
    @Transactional
    public void del(Long id) {
        //要删除对应的logininfo表中的信息
        logininfoMapper.del(employeeMapper.queryOne(id).getLogininfo_id());
        //再删中间表
        employeeMapper.delEmploymRole(id);
        super.del(id);
    }

    @Override
    public void patchDel(List<Long> ids) {
        for(Long id:ids){
            //要删除对应的logininfo表中的信息
            logininfoMapper.del(employeeMapper.queryOne(id).getLogininfo_id());
            //再删中间表
            employeeMapper.delEmploymRole(id);
        }
        super.patchDel(ids);
    }
}
//java.lang.Long, java.lang.String,  java.lang.String, java.lang.String, java.lang.Integer, java.lang.Long,
//        java.lang.Long, java.lang.Long, java.lang.String, java.lang.Long, java.lang.String]